package com.game.shudu

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class About : AppCompatActivity() {
    private lateinit var mWebView: WebView

    companion object {
        const val WEB_URL = "https://baike.baidu.com/item/%E6%A0%87%E5%87%86%E6%95%B0%E7%8B%AC%E6%8A%80%E5%B7%A7"
        val TAG = About::class.simpleName  //定义Log的TAG
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initAndSetupView()
        setContentView(mWebView)
        supportActionBar!!.hide()  //隐藏ActionBar
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initAndSetupView() {
        mWebView = WebView(applicationContext)
        val webSettings = mWebView.settings
        webSettings.javaScriptEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.allowFileAccess = true// 设置允许访问文件数据
        webSettings.setSupportZoom(true)//支持缩放
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true
        mWebView.setOnKeyListener(OnKeyEvent)
        mWebView.webViewClient = webClient
        mWebView.loadUrl(WEB_URL)
    }

    private val webClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            Log.d(TAG, url)
            return false
        }
    }

    private val OnKeyEvent = View.OnKeyListener { v, keyCode, event ->
        val action = event.action
        val webView = v as WebView
        if (KeyEvent.ACTION_DOWN == action && KeyEvent.KEYCODE_BACK == keyCode) {
            if (webView.canGoBack()) {
                webView.goBack()
                return@OnKeyListener true
            }
        }
        false
    }

    override fun onResume() {
        super.onResume()
        mWebView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mWebView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mWebView.clearCache(true)
        mWebView.stopLoading()
        mWebView.webViewClient = null
        mWebView.webChromeClient = null
        mWebView.removeAllViews()
        mWebView.destroy()
    }
}